/*
 * @Author: Leung
 * @Date: 2025-08-07 22:00:44
 * @LastEditTime: 2025-08-07 23:17:14
 * @FilePath: \Projecte:\STM32F103ZET6\STM32_Project_Peripheral_modules\EEPROM_AT24C02\I2C_Hardware\User\main.c
 * @Description: 
 * 
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved. 
 */
#include "stm32f10x.h"   // 相当于51单片机中的  #include <reg51.h>
#include "bsp_led.h"
#include "bsp_usart.h"
#include "bsp_i2c_ee.h"
#include <string.h>

#define  EEP_Firstpage      0x00    //WORD ADDRESS
uint8_t I2C_Buf_Write[256];
uint8_t I2C_Buf_Read[256];
uint8_t I2C_Test(void);


/**
  * @brief  主函数
  * @param  无
  * @retval 无
  */
int main(void)
{ 
  LED_GPIO_Config();
  
  LED_GREEN;
  
  /*初始化USART 配置模式为 115200 8-N-1，中断接收*/
  USART_Config();
  
	/* 发送一个字符串 */
	printf("This is an I2C peripheral (AT24C02) read-write test routine. \r\n");
	
	//初始化IIC
	I2C_EE_Init();
  
  /* EEPROM 读写测试 */
  if(I2C_Test() == 1)
  {
    LED_BLUE;
  }
  else
  {
    LED_RED;
  }
  
	while(1)
	{
		
	}
}


/**
* @brief I2C(AT24C02) 读写测试
* @param 无
* @retval 正常返回1 ，不正常返回0
*/
uint8_t I2C_Test(void)
{
  uint16_t i;
  
  EEPROM_INFO("\nWrite the following data:");
  
  for(i = 0; i < 256; i++)  //填充缓冲pBuffer
  {
    I2C_Buf_Write[i] = i;
    printf(" %02X ", I2C_Buf_Write[i]);
    if(i % 16 == 15)
      printf("\n");
  }
  
  /* 将I2c_Buf_Write中顺序递增的数据写入EERPOM中 */
  EEPROM_Buffer_Write(I2C_Buf_Write, EEP_Firstpage, 256);
  
  EEPROM_INFO("\nWrite EEPROM successfully.\n\r");
  
  EEPROM_INFO("\nRead EEPROM successfully.\n\r");
  
  EEPROM_Buffer_Read(I2C_Buf_Read, EEP_Firstpage, 256);
  
  //将I2c_Buf_Read中的数据通过串口打印
  for(i = 0; i < 256; i++)
  {
    if(I2C_Buf_Read[i] != I2C_Buf_Write[i])
    {
      EEPROM_ERROR("Error at Adrr: 0x%04X, Expected: 0x%02X, Read: 0x%02X\r\n", i, I2C_Buf_Read[i], I2C_Buf_Write[i]);
      return 0;
    }
    printf(" %02X ", I2C_Buf_Read[i]);
    if(i % 16 == 15)
      printf("\n");
  }
  EEPROM_INFO("\nEEPROM read and written test successfully!\r\n");
  return 1;
}

